<?php

namespace App\Http\Controllers\Api;

use App\Models\School;
use App\Models\WorkUser;
use App\Models\WorkTicket;
use App\Traits\ApiResponse;
use Illuminate\Http\Request;
use App\Models\WorkTicketImage;
use Illuminate\Validation\Rule;
use App\Models\WorkTicketDetail;
use App\Models\WorkTicketTransfer;
use Illuminate\Support\Facades\DB;
use App\Enums\WorkTicketStatusEnum;
use App\Http\Controllers\Controller;
use App\Events\WorkTicketTransferEvent;
use App\Http\Resources\WorkUserResource;
use Illuminate\Support\Facades\Validator;
use App\Http\Resources\WorkTicketResource;
use App\Enums\WorkTicketTransferStatusEnum;
use App\Events\WorkTicketTransferRejectEvent;
use App\Events\WorkTicketTransferSucessEvent;
use Illuminate\Validation\ValidationException;
use App\Http\Resources\WorkTicketTransferResource;
use Illuminate\Database\Eloquent\ModelnotFoundException;

/**
 * @OA\Tag(
 *     name="工单管理",
 *     description="工单相关接口"
 * )
 */
class WorkTicketController extends Controller
{
    use ApiResponse;

    /**
     * @OA\Get(
     *     path="/api/work-tickets",
     *     summary="获取工单列表",
     *     description="获取维护人员的工单列表，支持分页、搜索和筛选",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="school_id",
     *         in="query",
     *         description="学校ID",
     *         required=false,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Parameter(
     *         name="search",
     *         in="query",
     *         description="搜索关键词（工单编号、内容、房间号、联系人姓名、联系人电话）",
     *         required=false,
     *         @OA\Schema(type="string", example="空调")
     *     ),
     *     @OA\Parameter(
     *         name="status",
     *         in="query",
     *         description="工单状态|100：待处理,101：处理中,102：已处理,103：已取消",
     *         required=false,
     *         @OA\Schema(type="integer", example=100)
     *     ),
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         required=false,
     *         @OA\Schema(type="integer", default=1, example=1)
     *     ),
     *     @OA\Parameter(
     *         name="size",
     *         in="query",
     *         description="每页数量",
     *         required=false,
     *         @OA\Schema(type="integer", default=10, example=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="count", type="integer", description="总数", example=100),
     *                 @OA\Property(property="list", type="array", description="工单列表",
     *                     @OA\Items(ref="#/components/schemas/WorkTicketResource")
     *                 )
     *             ),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function index(Request $request)
    {
        $workUser = $request->attributes->get('work_user');

        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $validated = Validator::make($request->all(), [
            'school_id' => [
                'sometimes',
                'nullable',
                Rule::exists(School::class, School::ID)->whereNull(School::DELETED_AT)
            ],
            'search' => ['sometimes', 'nullable', 'string', 'max:255'],
            'status' => ['sometimes', 'nullable', Rule::in(WorkTicketStatusEnum::asArray())],
            'page' => ['sometimes', 'nullable', 'integer', 'min:1'],
            'size' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:100']
        ], [
            'school_id.exists' => '学校不存在',
            'search.string' => '搜索内容必须是字符串',
            'search.max' => '搜索内容不能超过255个字符',
            'status.in' => '状态必须是以下值之一: ' . implode(', ', WorkTicketStatusEnum::asArray()),
            'page.integer' => '页码必须是整数',
            'page.min' => '页码必须大于0',
            'size.integer' => '每页数量必须是整数',
            'size.min' => '每页数量必须大于0',
            'size.max' => '每页数量不能超过100'
        ]);

        if ($validated->fails()) {
            return $this->failed($validated->errors()->first());
        }

        $schoolId = $request->input('school_id');
        $search = $request->input('search');
        $status = $request->input('status');

        $query = WorkTicket::query()
            ->where(WorkTicket::WORK_USER_ID, $workUser->id)
            ->with(['school', 'schoolUser', 'workUser', 'transfers']);

        if ($schoolId) {
            $query->where(WorkTicket::SCHOOL_ID, $schoolId);
        }

        if ($search) {
            $query->where(function ($query) use ($search) {
                $query->where(WorkTicket::CODE, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::CONTENT, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::ROOM_NUMBER, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::CONTACT_NAME, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::CONTACT_TEL, 'like', '%' . $search . '%');
            });
        }

        if ($status) {
            $query->where(WorkTicket::STATUS, $status);
        }

        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $count = $query->count();

        $workTickets = $query->orderBy(WorkTicket::CREATED_AT, 'desc')
            ->forPage($page, $size)
            ->get();

        return $this->success([
            'count' => $count,
            'list' => WorkTicketResource::collection($workTickets)
        ]);
    }

    /**
     * @OA\Get(
     *     path="/api/work-tickets/{id}",
     *     summary="获取工单详情",
     *     description="获取指定工单的详情信息",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="工单ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object", ref="#/components/schemas/WorkTicketResource"),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="工单不存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="notFound"),
     *             @OA\Property(property="code", type="integer", example=404),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="工单不存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function show(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        try {
            // getSql();
            $workTicket = WorkTicket::query()
                ->with(['school', 'schoolUser', 'workUser', 'details', 'details.images', 'details.related', 'transfers', 'rating'])
                // ->where(WorkTicket::WORK_USER_ID, $workUser->id)
                ->where(function ($query) use ($workUser) {
                    $query->where(WorkTicket::WORK_USER_ID, $workUser->id)
                        ->orWhereHas('transfers', function ($query) use ($workUser) {
                            $query->where(WorkTicketTransfer::TO_WORK_USER_ID, $workUser->id)
                                ->where(WorkTicketTransfer::STATUS, WorkTicketTransferStatusEnum::待接受);
                        });
                })
                ->findOrFail($id);
        } catch (ModelNotFoundException $e) {
            return $this->notFound('工单不存在');
        }

        return $this->success(new WorkTicketResource($workTicket));
    }

    /**
     * @OA\Put(
     *     path="/api/work-tickets/{id}",
     *     summary="提交工单信息",
     *     description="提交指定工单的详情信息",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="工单ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="integer", example=100),
     *             @OA\Property(property="content", type="string", example="工单内容"),
     *             @OA\Property(property="images", type="array", @OA\Items(type="string", example="http://example.com/image.jpg"))
     *         ),
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="工单修改成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="工单不存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="notFound"),
     *             @OA\Property(property="code", type="integer", example=404),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="工单不存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function update(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }
        try {
            $validateData = $this->validate($request, [
                'status' => ['required', Rule::in(WorkTicketStatusEnum::asArray())],
                'content' => ['required', 'string', 'max:255'],
                'images' => ['sometimes', 'nullable', 'array'],
                'images.*' => ['sometimes', 'nullable', 'string', 'max:255'],
            ], [
                'status.required' => '状态不能为空',
                'status.in' => '状态必须是以下值之一: ' . implode(', ', WorkTicketStatusEnum::asArray()),
                'content.required' => '内容不能为空',
                'content.string' => '内容必须是字符串',
                'content.max' => '内容不能超过255个字符',
            ]);

            $workTicket = WorkTicket::query()
                ->where(WorkTicket::WORK_USER_ID, $workUser->id)
                ->findOrFail($id);

            if ($workTicket->status == WorkTicketStatusEnum::已处理) {
                return $this->failed('工单已处理，无法修改');
            }

            if ($workTicket->status == WorkTicketStatusEnum::已取消) {
                return $this->failed('工单已取消，无法修改');
            }

            DB::beginTransaction();

            $workTicketDetails = new WorkTicketDetail();
            $workTicketDetails->work_ticket_id = $workTicket->id;
            $workTicketDetails->content = $validateData['content'];
            $workTicketDetails->related_id = $workUser->id;
            $workTicketDetails->related_type = WorkUser::class;
            $workTicketDetails->save();

            if ($validateData['images'] && count($validateData['images']) > 0) {
                // 在数组中加入key
                $images = array_map(function ($image) use ($workTicketDetails, $id) {
                    return [
                        'path' => $image,
                        'work_ticket_detail_id' => $workTicketDetails->id,
                        'work_ticket_id' => $id
                    ];
                }, $validateData['images']);
                WorkTicketImage::insert($images);
            }

            if ($validateData['status'] == WorkTicketStatusEnum::已处理) {
                $workTicket->finish_at = now();
                $workTicket->save();
            }

            DB::commit();
            return $this->success('工单修改成功');
        } catch (ValidationException $e) {
            DB::rollBack();
            return $this->failed($e->validator->errors()->first());
        } catch (ModelnotFoundException $e) {
            DB::rollBack();
            return $this->notFound('工单不存在');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->failed('工单修改失败');
        }
    }

    /**
     * @OA\Post(
     *     path="/api/work-tickets/{id}/transfer",
     *     summary="转接工单",
     *     description="转接指定工单",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="工单ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\RequestBody(
     *         required=true,
     *         @OA\JsonContent(
     *             @OA\Property(property="to_work_user_id", type="integer", example=1),
     *             @OA\Property(property="remark", type="string", example="转接原因")
     *         )
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="工单已转接,等待转接人员确认")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="工单不存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="notFound"),
     *             @OA\Property(property="code", type="integer", example=404),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="工单不存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function transfer(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $workTicket = WorkTicket::where(WorkTicket::WORK_USER_ID, $workUser->id)
            ->where(WorkTicket::ID, $id)
            ->first();

        if (!$workTicket instanceof WorkTicket) {
            return $this->notFound('工单不存在');
        }

        if ($workTicket->status == WorkTicketStatusEnum::已处理) {
            return $this->failed('工单已处理，无法转接');
        }

        if ($workTicket->status == WorkTicketStatusEnum::已取消) {
            return $this->failed('工单已取消，无法转接');
        }

        if ($workTicket->transfers()->where('status', WorkTicketTransferStatusEnum::待接受)->exists()) {
            return $this->failed('工单已转接，无法再次转接');
        }

        $toWorkUserId = $request->input('to_work_user_id');
        if (!$toWorkUserId) {
            return $this->failed('转接人员ID不能为空');
        }

        if ($toWorkUserId == $workUser->id) {
            return $this->failed('不能转接给自己');
        }

        $toWorkUser = WorkUser::whereId($toWorkUserId)->first();
        if (!$toWorkUser instanceof WorkUser) {
            return $this->notFound('转接人员不存在');
        }

        // if ($toWorkUser->schools()->where('school_id', $workTicket->school_id)->doesntExist()) {
        //     return $this->failed('转接人员不属于该学校');
        // }

        $workTicketTransfer = new WorkTicketTransfer();
        $workTicketTransfer->work_ticket_id = $workTicket->id;
        $workTicketTransfer->from_work_user_id = $workUser->id;
        $workTicketTransfer->to_work_user_id = $toWorkUser->id;
        $workTicketTransfer->status = WorkTicketTransferStatusEnum::待接受;
        $workTicketTransfer->remark = $request->input('remark', '');
        $workTicketTransfer->save();

        event(new WorkTicketTransferEvent($workTicketTransfer));

        return $this->success('工单已转接,等待转接人员确认');
    }

    /**
     * @OA\Get(
     *     path="/api/work-tickets/my-transfer-list",
     *     summary="获取我的转接列表",
     *     description="获取我的转接列表",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         required=false,
     *         @OA\Schema(type="integer", default=1, example=1)
     *     ),
     *     @OA\Parameter(
     *         name="size",
     *         in="query",
     *         description="每页数量",
     *         required=false,
     *         @OA\Schema(type="integer", default=10, example=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="count", type="integer", description="总数", example=100),
     *                 @OA\Property(property="list", type="array", description="转接列表",
     *                     @OA\Items(ref="#/components/schemas/WorkTicketTransferResource")
     *                 )
     *             ),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function getMyTransferList(Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $page = $request->input('page', 1);
        $size = $request->input('size', 10);

        $query = WorkTicketTransfer::where(WorkTicketTransfer::TO_WORK_USER_ID, $workUser->id)
            ->where(WorkTicketTransfer::STATUS, WorkTicketTransferStatusEnum::待接受)
            ->with(['fromWorkUser', 'toWorkUser']);

        $count = $query->count();

        $list = $query->forPage($page, $size)->get();

        return $this->success([
            'count' => $count,
            'list' => WorkTicketTransferResource::collection($list)
        ]);
    }

    /**
     * @OA\Get(
     *     path="/api/work-tickets/my-transfer-detail/{id}",
     *     summary="获取我的转接详情",
     *     description="获取我的转接详情",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="转接记录ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object", ref="#/components/schemas/WorkTicketTransferResource"),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="转接记录不存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="notFound"),
     *             @OA\Property(property="code", type="integer", example=404),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="转接记录不存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function getMyTransferDetail(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $workTicketTransfer = WorkTicketTransfer::where(WorkTicketTransfer::TO_WORK_USER_ID, $workUser->id)
            ->where(WorkTicketTransfer::ID, $id)
            ->with(['workTicket', 'fromWorkUser', 'toWorkUser'])
            ->first();

        if (!$workTicketTransfer instanceof WorkTicketTransfer) {
            return $this->notFound('转接记录不存在');
        }

        return $this->success(new WorkTicketTransferResource($workTicketTransfer));
    }

    /**
     * @OA\Post(
     *     path="/api/work-tickets/my-transfer-detail/{id}/accept",
     *     summary="接受转接",
     *     description="接受转接",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="转接记录ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="转接记录已接受")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="转接记录不存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="notFound"),
     *             @OA\Property(property="code", type="integer", example=404),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="转接记录不存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function acceptTransfer(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $workTicketTransfer = WorkTicketTransfer::where(WorkTicketTransfer::TO_WORK_USER_ID, $workUser->id)
            ->where(WorkTicketTransfer::ID, $id)
            ->with(['workTicket'])
            ->first();

        if (!$workTicketTransfer instanceof WorkTicketTransfer) {
            return $this->notFound('转接记录不存在');
        }

        if ($workTicketTransfer->status != WorkTicketTransferStatusEnum::待接受) {
            return $this->failed('转接记录状态不正确');
        }

        $workTicketTransfer->status = WorkTicketTransferStatusEnum::已接受;
        $workTicketTransfer->accept_at = now();
        $workTicketTransfer->save();

        $workTicket = $workTicketTransfer->workTicket;
        $workTicket->work_user_id = $workTicketTransfer->from_work_user_id;
        $workTicket->save();

        event(new WorkTicketTransferSucessEvent($workTicketTransfer));

        return $this->success('转接记录已接受');
    }

    /**
     * @OA\Post(
     *     path="/api/work-tickets/my-transfer-detail/{id}/reject",
     *     summary="拒绝转接",
     *     description="拒绝转接",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="转接记录ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="转接记录已拒绝")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=404,
     *         description="转接记录不存在",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="notFound"),
     *             @OA\Property(property="code", type="integer", example=404),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="转接记录不存在")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function rejectTransfer(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $workTicketTransfer = WorkTicketTransfer::where(WorkTicketTransfer::TO_WORK_USER_ID, $workUser->id)
            ->where(WorkTicketTransfer::ID, $id)
            ->first();

        if (!$workTicketTransfer instanceof WorkTicketTransfer) {
            return $this->notFound('转接记录不存在');
        }

        if ($workTicketTransfer->status != WorkTicketTransferStatusEnum::待接受) {
            return $this->failed('转接记录状态不正确');
        }

        $workTicketTransfer->status = WorkTicketTransferStatusEnum::已拒绝;
        $workTicketTransfer->reject_at = now();
        $workTicketTransfer->save();

        event(new WorkTicketTransferRejectEvent($workTicketTransfer));

        return $this->success('转接记录已拒绝');
    }


    /**
     * @OA\Get(
     *     path="/api/work-tickets/worker-list",
     *     summary="获取维护人员列表",
     *     description="获取维护人员列表，支持按姓名搜索和分页",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="search",
     *         in="query",
     *         description="搜索关键词（维护人员姓名）",
     *         required=false,
     *         @OA\Schema(type="string", example="李师傅")
     *     ),
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         required=false,
     *         @OA\Schema(type="integer", default=1, example=1)
     *     ),
     *     @OA\Parameter(
     *         name="size",
     *         in="query",
     *         description="每页数量",
     *         required=false,
     *         @OA\Schema(type="integer", default=10, example=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="count", type="integer", description="总数", example=100),
     *                 @OA\Property(property="list", type="array", description="维护人员列表",
     *                     @OA\Items(ref="#/components/schemas/WorkUserResource")
     *                 )
     *             ),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function workerList(Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $validated = Validator::make($request->all(), [
            'search' => ['sometimes', 'nullable', 'string', 'max:255'],
            'page' => ['sometimes', 'nullable', 'integer', 'min:1'],
            'size' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:100']
        ], [
            'search.string' => '搜索内容必须是字符串',
            'search.max' => '搜索内容不能超过255个字符',
            'page.integer' => '页码必须是整数',
            'page.min' => '页码必须大于0',
            'size.integer' => '每页数量必须是整数',
            'size.min' => '每页数量必须大于0',
            'size.max' => '每页数量不能超过100'
        ]);

        if ($validated->fails()) {
            return $this->failed($validated->errors()->first());
        }

        $search = $request->input('search');
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);

        $query = WorkUser::query();

        if ($search) {
            $query->where(WorkUser::REAL_NAME, 'like', '%' . $search . '%');
        }

        $count = $query->count();

        $list = $query->forPage($page, $size)->get();

        return $this->success([
            'count' => $count,
            'list' => WorkUserResource::collection($list)
        ]);
    }


    /**
     * @OA\Get(
     *     path="/api/work-tickets/free-worker-list",
     *     summary="获取抢单列表",
     *     description="获取抢单列表，支持按姓名搜索和分页",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="school_id",
     *         in="query",
     *         description="学校ID",
     *         required=false,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Parameter(
     *         name="search",
     *         in="query",
     *         description="搜索关键词（维护人员姓名）",
     *         required=false,
     *         @OA\Schema(type="string", example="李师傅")
     *     ),
     *     @OA\Parameter(
     *         name="status",
     *         in="query",
     *         description="状态",
     *         required=false,
     *         @OA\Schema(type="string", example="1")
     *     ),
     *     @OA\Parameter(
     *         name="page",
     *         in="query",
     *         description="页码",
     *         required=false,
     *         @OA\Schema(type="integer", default=1, example=1)
     *     ),
     *     @OA\Parameter(
     *         name="size",
     *         in="query",
     *         description="每页数量",
     *         required=false,
     *         @OA\Schema(type="integer", default=10, example=10)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object",
     *                 @OA\Property(property="count", type="integer", description="总数", example=100),
     *                 @OA\Property(property="list", type="array", description="抢单列表",
     *                     @OA\Items(ref="#/components/schemas/WorkTicketResource")
     *                 )
     *             ),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function getFreeWorkerList(Request $request)
    {

        $validated = Validator::make($request->all(), [
            'school_id' => [
                'sometimes',
                'nullable',
                Rule::exists(School::class, School::ID)->whereNull(School::DELETED_AT)
            ],
            'search' => ['sometimes', 'nullable', 'string', 'max:255'],
            'status' => ['sometimes', 'nullable', Rule::in(WorkTicketStatusEnum::asArray())],
            'page' => ['sometimes', 'nullable', 'integer', 'min:1'],
            'size' => ['sometimes', 'nullable', 'integer', 'min:1', 'max:100']
        ], [
            'school_id.exists' => '学校不存在',
            'search.string' => '搜索内容必须是字符串',
            'search.max' => '搜索内容不能超过255个字符',
            'status.in' => '状态必须是以下值之一: ' . implode(', ', WorkTicketStatusEnum::asArray()),
            'page.integer' => '页码必须是整数',
            'page.min' => '页码必须大于0',
            'size.integer' => '每页数量必须是整数',
            'size.min' => '每页数量必须大于0',
            'size.max' => '每页数量不能超过100'
        ]);

        if ($validated->fails()) {
            return $this->failed($validated->errors()->first());
        }

        $schoolId = $request->input('school_id');
        $search = $request->input('search');
        $status = $request->input('status');

        $query = WorkTicket::query()
            ->where(function ($query) {
                $query->where(WorkTicket::WORK_USER_ID, 0)
                    ->orWhereNull(WorkTicket::WORK_USER_ID);
            })
            ->with(['school', 'schoolUser', 'workUser', 'transfers']);

        if ($schoolId) {
            $query->where(WorkTicket::SCHOOL_ID, $schoolId);
        }

        if ($search) {
            $query->where(function ($query) use ($search) {
                $query->where(WorkTicket::CODE, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::CONTENT, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::ROOM_NUMBER, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::CONTACT_NAME, 'like', '%' . $search . '%')
                    ->orWhere(WorkTicket::CONTACT_TEL, 'like', '%' . $search . '%');
            });
        }

        if ($status) {
            $query->where(WorkTicket::STATUS, $status);
        }

        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $count = $query->count();

        $workTickets = $query->orderBy(WorkTicket::CREATED_AT, 'desc')
            ->forPage($page, $size)
            ->get();

        return $this->success([
            'count' => $count,
            'list' => WorkTicketResource::collection($workTickets)
        ]);
    }

    /**
     * @OA\Post(
     *     path="/api/work-tickets/free-worker-list/{id}/accept",
     *     summary="抢单",
     *     description="抢单",
     *     tags={"工单管理"},
     *     security={{"bearerAuth":{}}},
     *     @OA\Parameter(
     *         name="id",
     *         in="path",
     *         description="工单ID",
     *         required=true,
     *         @OA\Schema(type="integer", example=1)
     *     ),
     *     @OA\Response(
     *         response=200,
     *         description="成功",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="success"),
     *             @OA\Property(property="code", type="integer", example=200),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="操作成功")
     *         )
     *     ),
     *     @OA\Response(
     *         response=400,
     *         description="参数校验失败",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="failed"),    
     *             @OA\Property(property="code", type="integer", example=400),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="参数校验失败")
     *         )
     *     ),
     *     @OA\Response(
     *         response=401,
     *         description="未授权",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="unauthorized"),
     *             @OA\Property(property="code", type="integer", example=401),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="未登录或登录已失效")
     *         )
     *     ),
     *     @OA\Response(
     *         response=500,
     *         description="服务器错误",
     *         @OA\JsonContent(
     *             @OA\Property(property="status", type="string", example="error"),
     *             @OA\Property(property="code", type="integer", example=500),
     *             @OA\Property(property="data", type="object"),
     *             @OA\Property(property="message", type="string", example="服务器内部错误")
     *         )
     *     )
     * )
     */
    public function acceptFreeWorkTicket(int $id, Request $request)
    {
        $workUser = $request->attributes->get('work_user');
        if (!$workUser instanceof WorkUser) {
            return $this->failed('维护人员不存在');
        }

        $workTicket = WorkTicket::where(WorkTicket::ID, $id)->first();
        if (!$workTicket instanceof WorkTicket) {
            return $this->notFound('工单不存在');
        }

        if ($workTicket->work_user_id != 0 && !is_null($workTicket->work_user_id)) {
            return $this->failed('工单已有人接单');
        }

        $workTicket->work_user_id = $workUser->id;
        $workTicket->save();

        return $this->success('抢单成功');
    }
}
